'use strict';
const sha1 = require("sha1");
const token = "clouddemo";
const db = uniCloud.database();
// 签名校验
function verifyMSGSender(params){
  const mysignature = sha1([token,params.timestamp,params.nonce].sort().join(""));
  
  console.log(mysignature===params.signature?"校验通过":"校验失败");
  
  if(mysignature===params.signature)return true;
  else return false;
}
exports.main = async (event, context) => {
	//event为客户端上传的参数
	// console.log('event : ', event)
	if(!verifyMSGSender(event.queryStringParameters)) return "来源校验失败";
	// 校验通过后,原样返回 echostr 参数内容，则接入生效，成为开发者成功，否则接入失败；接入成功后，注释下面代码
	// else return event.queryStringParameters.echostr;
	// 解析json格式字符串
	const receiveMsg = JSON.parse(event.body);
	console.log(receiveMsg)
	// 获取数据库中的access_token
	let data=await db.collection('setconfig').get()
	// console.log(data,data.data[0].accessToken,data.data[0]._id)
	// 官方的api， 总是出现bug
	// const apiUrl=`https://api.weixin.qq.com/cgi-bin/message/custom/business/send?access_token=${data.data[0].accessToken}`
	const apiUrl=`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${data.data[0].accessToken}`
	// console.log(apiUrl)
	let replyData={};
	//  根据用户发送的消息类型，做相应回应
	if(receiveMsg.MsgType=='event'){
		if(receiveMsg.Event=='user_enter_tempsession'){//用户刚进入聊天会话
			replyData={
				touser: receiveMsg.FromUserName, //接收此消息用户的openid
				msgtype:'text',
				text:{
					content:'欢迎大佬进入客服'
				}
			} 
		}else if(receiveMsg.Event=='kf_create_session'){//用户接入人工客服
			replyData={
				touser: receiveMsg.FromUserName, //接收此消息用户的openid
				msgtype:'text',
				text:{
					content:'已接入人工客服'
				}
			} 
		}else if(receiveMsg.Event=='kf_close_session'){//人工客服关闭
			replyData={
				touser: receiveMsg.FromUserName, //接收此消息用户的openid
				msgtype:'text',
				text:{
					content:'人工会话已关闭'
				}
			} 
		}
		
	}else if(receiveMsg.MsgType=='text'){
		if(receiveMsg.Content=='link'){//图文链接
			replyData={
				touser: receiveMsg.FromUserName, //接收此消息用户的openid
				msgtype:'link',
				link:{
					title:'官网',
					description:"看一下官网啥样子啊",
					url:'https://mobile.shoyii.com/#/',
					thumb_url:'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-62ec721a-a0ff-4726-a9f0-0e206b972095/e57222df-3110-48d9-9c73-ce19fab8983c.jpg',
				}
			} 
		}else if(receiveMsg.Content=='miniprogrampage'){//小程序卡片
			let res=await db.collection('mini-media-demo').get({getOne:true})
			// console.log(res,123) 
			replyData={
				touser: receiveMsg.FromUserName, //接收此消息用户的openid
				msgtype:'miniprogrampage',
				miniprogrampage:{
					title:'小程序卡片',
					pagepath:'pages/index/index',
					thumb_media_id:res.data[4].media_id
				}
			} 
		}else if(receiveMsg.Content=='image'){//图片	
			let res=await db.collection('mini-media-demo').get({getOne:true})
			// console.log(res,123) 
			replyData={
				touser: receiveMsg.FromUserName, //接收此消息用户的openid
				msgtype:'image',
				image:{
					media_id:res.data[1].media_id
				}
			} 
		}else if(receiveMsg.Content=='miniprogramtext'){//小程序文字链接	
			replyData={
				touser: receiveMsg.FromUserName, //接收此消息用户的openid
				msgtype:'text',
				text:{
					content:'来啊，<a data-miniprogram-appid="wxf03b6cf75fa949c9" data-miniprogram-path="pages/index/index">点击进入小程序</a>'
				}
			} 
		}
		else if(receiveMsg.Content=='人工客服'){//转发到网页客服
			// replyData=`<xml> 
			//   <ToUserName><![CDATA[${receiveMsg.FromUserName}]]></ToUserName>
			//   <FromUserName><![CDATA[${receiveMsg.ToUserName}]]></FromUserName> 
			//   <CreateTime>${receiveMsg.CreateTime}</CreateTime>
			//   <MsgType><![CDATA[transfer_customer_service]]></MsgType>`
			// replyData+= '</xml>'
			replyData={
				// CreateTime: parseInt(+new Date / 1000),
				MsgType: "transfer_customer_service",
				ToUserName: receiveMsg.FromUserName,
				FromUserName: receiveMsg.ToUserName,
				CreateTime: receiveMsg.CreateTime
			}
			// 直接return出去，不需要调api发送
			return replyData
		}
		else{
			replyData={
				"touser": receiveMsg.FromUserName, //接收此消息用户的openid
				"msgtype":'text',
				"text":{
					"content":'哈喽啊'
				}
			} 
		}
		
	}else if(receiveMsg.MsgType=='image'){
		let res=await db.collection('mini-media-demo').get({getOne:true})
		console.log(res,123) 
		replyData={
			touser: receiveMsg.FromUserName, //接收此消息用户的openid
			msgtype:'image',
			image:{
				media_id:res.data[0].media_id
			}
		} 
	}
	// 发送客服消息
	const res = await uniCloud.httpclient.request(apiUrl, {
	    method: 'POST',
	    data:replyData,
	    contentType: 'json', // 指定以application/json发送data内的数据
	    dataType: 'json' // 指定返回值为json格式，自动进行parse
	})
	console.log(res)
	//返回数据给微信端
	return 'success';
};
